package com.smec.moblie.activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.acker.simplezxing.activity.CaptureActivity;
import com.bigkoo.alertview.AlertView;
import com.bigkoo.alertview.OnItemClickListener;
import com.google.gson.Gson;
import com.hwangjr.rxbus.Bus;
import com.hwangjr.rxbus.SmecRxBus;
import com.nineoldandroids.view.ViewHelper;
import com.smec.moblie.R;
import com.smec.moblie.SMECApplication;
import com.smec.moblie.adapter.LeftItemAdapter;
import com.smec.moblie.adapter.LeftItemIndividuationAdapter;
import com.smec.moblie.adapter.LeftItemMantrAdapter;
import com.smec.moblie.bean.AskActionBackBean;
import com.smec.moblie.bean.MaintenanceBean;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.control.PublicControl;
import com.smec.moblie.crash.ExitAppUtils;
import com.smec.moblie.fragment.MaintenanceListFragment;
import com.smec.moblie.fragment.TechnicalNoticeFragment;
import com.smec.moblie.glocation.LocationUpdateBean;
import com.smec.moblie.util.DateUtil;
import com.smec.moblie.util.FileUtil;
import com.smec.moblie.view.dialog.MonthSelectDialog;
import com.smec.moblie.view.dialog.MyDatePicker;
import com.smec.moblie.view.draglayout.DragLayout;
import com.smec.moblie.view.draglayout.DragLayout.DragListener;
import com.smec.remes.module.drafts.SmecDraftsFragment;
import com.smec.remes.module.query.list.SmecListFragment;
import com.smec.remes.module.query.mantr.SmecMantrFragment;
import com.smec.remes.module.query.packing.SmecPackingFragment;
import com.smec.remes.module.query.picture.SmecPictureFragment;
import com.smec.remes.module.register.SmecRegisterFragment;
import com.smec.remes.module.request.SmecRequestFragment;
import com.smec.remes.module.scan.SmecScanFragment;
import com.smec.remes.module.submit.SmecSubmitFragment;
import com.smec.remes.util.CommonUtils;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.litepal.crud.DataSupport;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Stack;

import cn.jpush.android.api.JPushInterface;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;

import static com.smec.remes.module.scan.SmecScanFragment.SCAN_SUCCESS;

/**
 * 保养列表页
 */
public class MainActivity extends BaseActivity {
    //侧边栏
    private DragLayout dragLayout;
    //侧边栏列表list
    private ListView leftItemLv;
    //侧边栏个性化保养list
    private ListView leftItemLv_individuation;
    private ListView leftItemLvMantr;
    //侧边栏头像
    private ImageView imageView_headportrait;
    //主页面头像
    private ImageView imageView_headportrait2;
    //标题
    public TextView textView_title;
    //用户名字显示
    private TextView textView_username;
    //日期筛选
    private TextView textView_datepicker;
    //月份筛选
    public TextView textView_monthPicker;
    //设置
    private LinearLayout layout_setup;
    //上传坐标
    private TextView textView_updateLocation;
    private ImageView imageViewClassification;
    private TextView textViewAll;
    private TextView textViewByCustomer;
    private TextView textViewByNo;
    // 用户id
    public static String USERNAME;
    //用户中文名
    private String TRUENAME;
    // 侧边栏项目值
    private String[] leftItems;
    //个性化保养项目值
    private String[] leftItemsIndividuation;
    //物料管理
    private String[] leftItemsMantr;
    // 退出时间记录
    private long exitTime = 0;
    // 侧边栏列表adapter
    private LeftItemAdapter leftItemAdapter;
    private LeftItemIndividuationAdapter leftItemIndividuationAdapter;
    private LeftItemMantrAdapter leftItemMantrAdapter;
    // 工单是否已完成
    private boolean isfinished = false;
    /**
     * 选择的月份
     **/
    private String sel_month = "";
    /**
     * 选择的日期
     **/
    private MyDatePicker datePicker;
    private RelativeLayout rl_title;
    public static boolean isNeedAskAction = true;
    private int tempUpdateLocationLog = 0;
    private String updateLocationDateString = null;
    private Boolean isUpdateTodayLocationDate = false;
    private PopupWindow popupWindow;
    private FragmentManager fm;
    public Fragment mContent;
    private MaintenanceListFragment maintenanceListFragment;
    private TechnicalNoticeFragment technicalNoticeFragment;
    private SharedPreferences mySharedPreferences;
    private SmecRequestFragment smecRequestFragment;
    private SmecSubmitFragment smecSubmitFragment;
    private SmecRegisterFragment smecRegisterFragment;
    private SmecDraftsFragment smecDraftsFragment;
    private SmecListFragment smecListFragment;
    private SmecPictureFragment smecPictureFragment;
    private SmecPackingFragment smecPackingFragment;
    private SmecMantrFragment smecMantrFragment;
    private SmecScanFragment smecScanFragment;

    protected Bus mRxBus;
    private boolean isExit=false;
    private static Stack<Activity> activityStack;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit=true;
        }
    };
    private TextView tv_query_list,tv_query_picture,tv_query_packing,tv_query_mantr;

    @Override
    protected void setContentView() {
        setContentView(R.layout.remes_act_mainlist);
        isShowVersionDialog = false;
        mRxBus= SmecRxBus.get();
        mRxBus.register(this);
        _intent();
    }

    /**
     * 查询工具跳转
     */
    public void _intent(){
        tv_query_list= (TextView) findViewById(R.id.tv_query_list);
        tv_query_list.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView_title.setText("库存清单查询");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecListFragment == null){
                    smecListFragment= SmecListFragment.newInstance();
                }
                switchContent(mContent, smecListFragment);
                dragLayout.close();
            }
        });
        tv_query_picture= (TextView) findViewById(R.id.tv_query_picture);
        tv_query_picture.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView_title.setText("常用备件图片查询");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecPictureFragment == null){
                    smecPictureFragment= SmecPictureFragment.newInstance();
                }
                switchContent(mContent, smecPictureFragment);
                dragLayout.close();
            }
        });
        tv_query_packing= (TextView) findViewById(R.id.tv_query_packing);
        tv_query_packing.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView_title.setText("成品装箱清单查询");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecPackingFragment == null){
                    smecPackingFragment= SmecPackingFragment.newInstance();
                }
                switchContent(mContent, smecPackingFragment);
                dragLayout.close();
            }
        });
        tv_query_mantr= (TextView) findViewById(R.id.tv_query_mantr);
        tv_query_mantr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView_title.setText("图号查物料号");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecMantrFragment == null){
                    smecMantrFragment= SmecMantrFragment.newInstance();
                }
                switchContent(mContent, smecMantrFragment);
                dragLayout.close();
            }
        });
    }

    private void setDefaultFragment() {
        maintenanceListFragment = new MaintenanceListFragment();
        technicalNoticeFragment = new TechnicalNoticeFragment();
        fm = getSupportFragmentManager();
        FragmentTransaction transaction = fm.beginTransaction();
        transaction.replace(R.id.maintenanceFragment, maintenanceListFragment);
        mContent = maintenanceListFragment;
        transaction.commit();
    }

    @Override
    protected void initView() {
        ExitAppUtils.getInstance().addActivity(this);
        rl_title = (RelativeLayout) findViewById(R.id.rl_title);
        EventBus.getDefault().register(this);//注册EventBus
        mySharedPreferences = getSharedPreferences(
                "ElevatorSharedPreferences", LoginActivity.MODE_PRIVATE);
        USERNAME = mySharedPreferences.getString("USERNAME", "");
        TRUENAME = mySharedPreferences.getString("TRUENAME", "");
        // 开始定位服务
        updateLocationDateString = mySharedPreferences.getString("UPDATELOCATIONDATESTRING", "");
        isUpdateTodayLocationDate = mySharedPreferences.getBoolean("ISUPDATETODAYLOCATIONDATE", false);
        if (!updateLocationDateString.equals(DateUtil.getTodayString())) {
            new ReadFileAsyncTask("MaintanceLog_Info" + DateUtil.getYesterday() + ".txt", 1).execute();
            // 实例化SharedPreferences.Editor对象
            SharedPreferences.Editor editor = mySharedPreferences
                    .edit();
            editor.putBoolean("ISUPDATETODAYLOCATIONDATE", false);
            // 提交当前数据
            editor.commit();
            isUpdateTodayLocationDate = false;
        }
        if (!isUpdateTodayLocationDate && DateUtil.isAfterThreePM()) {
            new ReadFileAsyncTask("MaintanceLog_Info" + DateUtil.getTodayString() + ".txt", 2).execute();
        }
        if (USERNAME.equals("")) {
            new AlertView("提示", "当前账号需要重新登入", null, new String[]{"确定"}, null, this, AlertView.Style.Alert, new OnItemClickListener() {
                @Override
                public void onItemClick(Object o, int position) {
                    if (position == 0) {
                        Intent intent = new Intent(MainActivity.this, LoginActivity.class);
                        startActivity(intent);
                        MainActivity.this.finish();
                    }
                }
            }).show();
        }
        AskActionService(USERNAME);

        // 获取侧滑列表项
        leftItems = this.getResources().getStringArray(R.array.leftItems);
        leftItemsIndividuation = this.getResources().getStringArray(R.array.leftItemsIndividuation);
        leftItemsMantr= this.getResources().getStringArray(R.array.leftItemsMantr);
        JPushInterface.setDebugMode(true);
        JPushInterface.init(this);
        // 调用JPush API设置Alias
        try {
            JPushInterface.setAliasAndTags(getApplicationContext(), USERNAME,
                    null);
        } catch (Exception e) {
        }
        initDragLayout();// 初始化侧边栏
        dragLayout = (DragLayout) findViewById(R.id.dragLayout);
        leftItemLv = (ListView) findViewById(R.id.leftItemLv);
        leftItemLvMantr= (ListView) findViewById(R.id.leftItemLv_mantr);
        leftItemLv_individuation = (ListView) findViewById(R.id.leftItemLv_individuation);
        imageView_headportrait = (ImageView) findViewById(R.id.imageView_headPortrait);
        imageView_headportrait2 = (ImageView) findViewById(R.id.imageView_headportrait2);
        textView_title = (TextView) findViewById(R.id.textView_title);
        textView_username = (TextView) findViewById(R.id.textView_username);
        leftItemAdapter = new LeftItemAdapter(MainActivity.this, leftItems);
        leftItemIndividuationAdapter = new LeftItemIndividuationAdapter(MainActivity.this, leftItemsIndividuation);
        imageView_headportrait2.setOnClickListener(this);
        textView_monthPicker = (TextView) findViewById(R.id.textView_monthPicker);
        textView_monthPicker.setOnClickListener(this);
        textView_datepicker = (TextView) findViewById(R.id.textView_datepicker);
        textView_datepicker.setOnClickListener(this);
        layout_setup = (LinearLayout) findViewById(R.id.layout_setup);
        layout_setup.setOnClickListener(this);
        textView_updateLocation = (TextView) findViewById(R.id.textView_updateLocation);
        textView_updateLocation.setOnClickListener(this);
        imageViewClassification = (ImageView) findViewById(R.id.imageViewClassification);
        imageViewClassification.setOnClickListener(this);
        //popwindow
        LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_bubble, null);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 1f;
                getWindow().setAttributes(lp);
            }
        });
        textViewAll = (TextView) contentview.findViewById(R.id.textViewAll);
        textViewByCustomer = (TextView) contentview.findViewById(R.id.textViewByCustomer);
        textViewByNo = (TextView) contentview.findViewById(R.id.textViewByNo);
        textViewAll.setOnClickListener(this);
        textViewByCustomer.setOnClickListener(this);
        textViewByNo.setOnClickListener(this);
        if(isShow()){
            String[] arr=new String[leftItemsMantr.length+1];
            for(int i=0;i<leftItemsMantr.length;i++){
                arr[i]=leftItemsMantr[i];
            }
            arr[arr.length-1]="站长收货";
            leftItemsMantr=null;
            leftItemsMantr=arr;
        }else {
            RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) leftItemLvMantr.getLayoutParams();
            params.height=260;
            leftItemLvMantr.setLayoutParams(params);
        }
        if(isStation()){
            leftItemMantrAdapter = new LeftItemMantrAdapter(MainActivity.this, leftItemsMantr);
        }else {
            RelativeLayout.LayoutParams params= (RelativeLayout.LayoutParams) leftItemLvMantr.getLayoutParams();
            params.height=0;
            leftItemLvMantr.setLayoutParams(params);
        }
    }

    private boolean isShow(){
        SharedPreferences mySharedPreferences=
                SMECApplication.getContext().getSharedPreferences("ElevatorSharedPreferences", LoginActivity.MODE_PRIVATE);
        String role=mySharedPreferences.getString("role","");
//        return role.contains("REMES_STATION_CAPTAIN");
        return true;
    }

    private boolean isStation(){
        SharedPreferences mySharedPreferences=
                SMECApplication.getContext().getSharedPreferences("ElevatorSharedPreferences", LoginActivity.MODE_PRIVATE);
        String isStation=mySharedPreferences.getString("isStation","");
//        return "Y".equals(isStation) ? true :false;
        return true;
    }

    @Override
    protected void getData() {
        textView_username.setText(TRUENAME);
        leftItemLv.setAdapter(leftItemAdapter);
        leftItemLv_individuation.setAdapter(leftItemIndividuationAdapter);
        leftItemLvMantr.setAdapter(leftItemMantrAdapter);
        setDefaultFragment();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.imageView_headportrait2:
                dragLayout.open();
                break;

            case R.id.textView_datepicker:
                if (textView_datepicker.getText().equals("取消筛选")) {
                    EventBus.getDefault().post(new EventCenter.CancelSelectDate());
                    textView_datepicker.setText("日期筛选");
                    textView_monthPicker.setText("全部");
                } else {
                    datePicker = new MyDatePicker(MainActivity.this,
                            new MyDatePicker.SubmitOperateDialogListener() {

                                @Override
                                public void onDateUnselected(Date date) {
                                }

                                @Override
                                public void onDateSelected(Date date) {
                                    String selectDate = DateUtil
                                            .getDateStringFromDate(date);
                                    textView_datepicker.setText("取消筛选");
                                    EventBus.getDefault().post(new EventCenter.SelectDate(selectDate));
                                    datePicker.dismiss();
                                }
                            });
                    datePicker.setTitle("请点击选择保养的日期");
                    WindowManager wm = MainActivity.this
                            .getWindowManager();
                    int width = wm.getDefaultDisplay().getWidth();
                    int height = wm.getDefaultDisplay().getHeight();
                    datePicker.show();
                    datePicker.getWindow().setLayout(width * 9 / 10,
                            height * 7 / 10);
                }
                break;

            case R.id.textView_monthPicker:
                if(!TextUtils.isEmpty(textView_monthPicker.getText().toString())&&textView_monthPicker.getText().toString().equals("编辑")){
                    mRxBus.post("quanxuan","success");
                }else if(!TextUtils.isEmpty(textView_monthPicker.getText().toString())&&textView_monthPicker.getText().toString().equals("取消")){
                    mRxBus.post("quanxuan","success");
                }else if(!TextUtils.isEmpty(textView_monthPicker.getText().toString())&&textView_monthPicker.getText().toString().equals("扫码")){
                    startActivityForResult(new Intent(MainActivity.this, CaptureActivity.class), CaptureActivity.REQ_CODE);
                }
                else {
                    MonthSelectDialog dialog = new MonthSelectDialog(
                            MainActivity.this);
                    sel_month = dialog.show();
                }
                break;

            case R.id.layout_setup:
                Intent intent = new Intent(MainActivity.this, SetUpActivity.class);
                startActivity(intent);

                break;
            case R.id.textView_updateLocation:

                break;
            case R.id.imageViewClassification:
                popupWindow.showAsDropDown(imageViewClassification, -138, 0);
                WindowManager.LayoutParams lp = getWindow().getAttributes();
                lp.alpha = 0.7f;
                getWindow().setAttributes(lp);
                break;

            case R.id.textViewAll:
                EventBus.getDefault().post(new EventCenter.TopSelector(ALL));
                textViewAll.setTextColor(Color.parseColor("#02c7c0"));
                textViewByCustomer.setTextColor(Color.parseColor("#333333"));
                textViewByNo.setTextColor(Color.parseColor("#333333"));
                popupWindow.dismiss();
                break;
            case R.id.textViewByCustomer:
                EventBus.getDefault().post(new EventCenter.TopSelector(BYCUSTOMER));
                textViewByCustomer.setTextColor(Color.parseColor("#02c7c0"));
                textViewByNo.setTextColor(Color.parseColor("#333333"));
                textViewAll.setTextColor(Color.parseColor("#333333"));
                popupWindow.dismiss();
                break;
            case R.id.textViewByNo:
                EventBus.getDefault().post(new EventCenter.TopSelector(BYNO));
                textViewByNo.setTextColor(Color.parseColor("#02c7c0"));
                textViewByCustomer.setTextColor(Color.parseColor("#333333"));
                textViewAll.setTextColor(Color.parseColor("#333333"));
                popupWindow.dismiss();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 消息bus解注
        EventBus.getDefault().unregister(this);
    }

    /**
     * 询问是否弹出调查问卷
     *
     * @param username
     */
    private void AskActionService(String username) {
        final Gson gson = new Gson();
        HashMap<String, Object> hashMap = new HashMap<>();
        hashMap.put("user", username);
        String jsonData = gson.toJson(hashMap);
        OkHttpUtils.postString().url(APP_ASKACTION_SERVICE_URL).content(jsonData).mediaType(MediaType.parse("application/json; charset=utf-8")).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                Log.i("AskActionService", "~~~ AskActionService Error = " + e.getMessage());
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    Log.i("AskActionService", "~~~ AskActionService response = " + response);
                    AskActionBackBean askActionBackBean = gson.fromJson(response.toString(), AskActionBackBean.class);
                    if (askActionBackBean.getAction().equals("OPEN_URL")) {
                        Intent intent = new Intent(MainActivity.this, AskActionActivity.class);
                        intent.putExtra("URL", askActionBackBean.getUrl());
                        intent.putExtra("CLOSE_URL", askActionBackBean.getClose_url());
                        startActivity(intent);
                    } else {
                        isNeedAskAction = false;
                    }
                } catch (Exception e) {
                    Log.i("AskActionService", "~~ AskActionService err = " + e.getMessage());
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }


        });
    }

    /**
     * 初始化侧边栏
     */
    private void initDragLayout() {
        dragLayout = (DragLayout) findViewById(R.id.dragLayout);
        dragLayout.setDragListener(new DragListener() {
            @Override
            public void onOpen() {
                CommonUtils.hideImmManager(dragLayout);
            }

            @Override
            public void onClose() {
            }

            @Override
            public void onDrag(float percent) {
                ViewHelper.setAlpha(imageView_headportrait2, 1 - percent);
                ViewHelper.setAlpha(imageView_headportrait, percent);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        JPushInterface.onPause(this);
    }

    /**
     * 两次退出
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(getApplicationContext(), "再按一次退出程序",
                        Toast.LENGTH_SHORT).show();
                mHandler.sendEmptyMessageDelayed(0, 2000);
            } else {
                finish();
                System.exit(0);
            }
        }
        return false;
    }

    /**
     * toast监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ToastMessage event) {
        String message = event.getMessage();
        Log.i("debug", "~~~~~ToastMessage=" + message);
        Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT)
                .show();
    }

    /**
     * 侧边栏选择监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ChangeList event) {
        int listId = event.getListId();
        Log.i("debug", "listId = " + listId);
        switch (listId) {
            case 0:
                textView_title.setText("未完成保养单");
                isfinished = false;
                switchContent(mContent, maintenanceListFragment);
                textView_monthPicker.setText("全部");
                textView_datepicker.setText("日期筛选");
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.VISIBLE);
                textView_monthPicker.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(
                        new EventCenter.ChangeIsFinsish(isfinished));
                break;
            case 1:
                textView_title.setText("已完成保养单");
                isfinished = true;
                switchContent(mContent, maintenanceListFragment);
                textView_monthPicker.setText("全部");
                textView_datepicker.setText("日期筛选");
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.VISIBLE);
                textView_monthPicker.setVisibility(View.VISIBLE);
                EventBus.getDefault().post(
                        new EventCenter.ChangeIsFinsish(isfinished));
                break;
            default:
                break;

        }
        dragLayout.close();
    }

    public void switchContent(Fragment from, Fragment to) {
        //开启事务，fragment的控制是由事务来实现的
        FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
        //第二种方式(replace)，初始化fragment
        transaction.replace(R.id.maintenanceFragment, to);
        //提交事务
        transaction.commit();

    }

    /**
     * 物料管理侧边栏选择监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ClickMantrList event) {
        int listId = event.getListId();
        Log.i("debug", "listId = " + listId);
        switch (listId) {
            case 0:
                textView_title.setText("物料申请");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecRequestFragment == null){
                    smecRequestFragment= SmecRequestFragment.newInstance();
                }
                switchContent(mContent, smecRequestFragment);
                break;
            case 1:
                textView_title.setText("已提交申请");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecSubmitFragment == null){
                    smecSubmitFragment= SmecSubmitFragment.newInstance();
                }
                switchContent(mContent, smecSubmitFragment);
                break;
            case 2:
                textView_title.setText("物料登记");
                textView_monthPicker.setText("");
                textView_monthPicker.setEnabled(false);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                if(smecRegisterFragment == null){
                    smecRegisterFragment= SmecRegisterFragment.newInstance();
                }
                switchContent(mContent, smecRegisterFragment);
                break;
            case 3:
                textView_title.setText("草稿箱");
                textView_monthPicker.setText("编辑");
                textView_monthPicker.setEnabled(true);
                textView_datepicker.setEnabled(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.VISIBLE);
                if(smecDraftsFragment == null){
                    smecDraftsFragment= SmecDraftsFragment.newInstance();
                }
                switchContent(mContent, smecDraftsFragment);
                break;
            case 4:
                textView_title.setText("站长收货");
                textView_monthPicker.setText("扫码");
                textView_monthPicker.setEnabled(true);
                textView_monthPicker.setVisibility(View.VISIBLE);
                textView_datepicker.setText("");
                textView_datepicker.setEnabled(false);
                textView_datepicker.setFocusableInTouchMode(false);
                imageViewClassification.setVisibility(View.GONE);
                textView_datepicker.setVisibility(View.GONE);
                if(smecScanFragment == null){
                    smecScanFragment= SmecScanFragment.newInstance();
                }
                switchContent(mContent, smecScanFragment);
                break;
            default:
                break;

        }
        dragLayout.close();
    }

    /**
     * 个性化保养侧边栏选择监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ClickIndividuationItem event) {
        int listId = event.getListId();
        Boolean isCompleted = false;
        Log.i("debug", "listId = " + listId);
        switch (listId) {
            case 0:
                textView_title.setText("未完成个性化保养单");
                isCompleted = false;
                try {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isCompleted", isCompleted);
                    technicalNoticeFragment.setArguments(bundle);
                } catch (Exception e) {

                }
                switchContent(mContent, technicalNoticeFragment);
                imageViewClassification.setVisibility(View.VISIBLE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                EventBus.getDefault().post(new EventCenter.ChangeTechnicalNoticeList(isCompleted));
                break;
            case 1:
                textView_title.setText("已完成个性化保养单");
                isCompleted = true;
                try {
                    Bundle bundle = new Bundle();
                    bundle.putBoolean("isCompleted", isCompleted);
                    technicalNoticeFragment.setArguments(bundle);
                } catch (Exception e) {

                }
                switchContent(mContent, technicalNoticeFragment);
                imageViewClassification.setVisibility(View.VISIBLE);
                textView_datepicker.setVisibility(View.GONE);
                textView_monthPicker.setVisibility(View.GONE);
                EventBus.getDefault().post(new EventCenter.ChangeTechnicalNoticeList(isCompleted));
                break;
            default:
                break;
        }
        dragLayout.close();
    }

    /**
     * 月份选择监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.SelectMonth event) {
        sel_month = event.getMonth();

        // 月份字段显示到界面
        if (sel_month != null) {
            if (!sel_month.equals("ALL")) {
                textView_monthPicker.setText(sel_month.substring(
                        sel_month.indexOf("/") + 1,
                        sel_month.length())
                        + "月");
            } else {
                textView_monthPicker.setText("全部");
            }

            textView_datepicker.setText("日期筛选");
        }
    }

    /**
     * 改变侧边栏数量监听
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ChangeLeftItems event) {

        new ChangeLeftItemsAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

    }

    /**
     * 改变侧边栏数量
     */
    private class ChangeLeftItemsAsyncTask extends android.os.AsyncTask<Void, Void, Void> {
        int unfinishNum;
        int finishedNum;

        @Override
        protected Void doInBackground(Void... params) {
            unfinishNum = DataSupport.where("(wo_status_code = 'EXECUTE' OR wo_status_code = 'SUBMITTED_WITHOUT_IMG') AND assignee = ? ", MainActivity.USERNAME).count(MaintenanceBean.class);
            finishedNum = DataSupport.where("wo_status_code = 'COMPLETED' AND assignee = ?", MainActivity.USERNAME).count(MaintenanceBean.class);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            leftItems[1] = "已完成保养单(" + finishedNum + ")";
            leftItems[0] = "未完成保养单(" + unfinishNum + ")";
            leftItemAdapter.setList(leftItems);
            super.onPostExecute(aVoid);
        }
    }

    private class ReadFileAsyncTask extends AsyncTask<Void, Void, Void> {
        int type;
        String fileName;
        String fileString;

        public ReadFileAsyncTask(String fileName, int type) {
            this.fileName = fileName;
            this.type = type;
        }

        @Override
        protected Void doInBackground(Void... params) {
            Log.e("log", "~~updateLog filename = " + fileName);
            fileString = FileUtil.readSDFile(fileName);
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            updateLog(fileString, fileName, type);
            super.onPostExecute(aVoid);
        }
    }

    private void updateLog(String fileString, final String fileName, final int type) {

        LocationUpdateBean.CrashLogEntity crashLogEntity = new LocationUpdateBean.CrashLogEntity();
        crashLogEntity.setAppUser(USERNAME);
        crashLogEntity.setCrashLog(fileString);
        crashLogEntity.setIMEI(android.os.Build.MODEL);
        crashLogEntity.setAppVersion(PublicControl.getAppVersionName(MainActivity.this));
        List<LocationUpdateBean.CrashLogEntity> crashLogEntities = new ArrayList<>();
        crashLogEntities.add(crashLogEntity);
        LocationUpdateBean locationUpdateBean = new LocationUpdateBean();
        locationUpdateBean.setCrashLog(crashLogEntities);
        Gson gson = new Gson();
        String jsonString = gson.toJson(locationUpdateBean);
        tempUpdateLocationLog++;

        OkHttpUtils.postString().url(CRASHUPLOADPATH2).content(jsonString).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e("log", "~~updateLog failed " + e.getMessage());
                if (tempUpdateLocationLog < 10) {
                    new ReadFileAsyncTask(fileName, type).execute();
                }
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response, int id) {
                Log.i("log", "~~updateLog back=" + response);
                if (response.indexOf("SUCCESS") == -1) {
                    if (tempUpdateLocationLog < 10) {
                        new ReadFileAsyncTask(fileName, type).execute();
                    }
                } else {
                    if (type == 1) {
                        updateLocationDateString = DateUtil.getTodayString();
                        // 实例化SharedPreferences.Editor对象
                        SharedPreferences.Editor editor = mySharedPreferences
                                .edit();
                        editor.putString("UPDATELOCATIONDATESTRING", updateLocationDateString);
                        // 提交当前数据
                        editor.commit();
                    } else if (type == 2) {
                        isUpdateTodayLocationDate = true;
                        SharedPreferences.Editor editor = mySharedPreferences
                                .edit();
                        editor.putBoolean("ISUPDATETODAYLOCATIONDATE", true);
                        // 提交当前数据
                        editor.commit();
                    }
                }
            }

            @Override
            public void onBefore(Request request, int id) {
                super.onBefore(request, id);
            }

            @Override
            public void onAfter(int id) {
                super.onAfter(id);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case CaptureActivity.REQ_CODE:
                switch (resultCode) {
                    case RESULT_OK:
                        Log.e("扫码",data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT));
                        String a=data.getStringExtra(CaptureActivity.EXTRA_SCAN_RESULT);
                        mRxBus.post(SCAN_SUCCESS,a);
                        break;
                    case RESULT_CANCELED:
                        if (data != null) {
                            Log.e("SSS","ssss");
                        }
                        break;
                }
                break;
        }
    }
}
